const express = require('express')
const app = express()

// 安装并配置跨域 cros
const cros = require('cors')
app.use(cros())

// 配置解析表单数据的中间价  注意：只能解析 application/x-www-form-urlencoded格式的表单数据
app.use(express.urlencoded({ extended: false }))  //固定写法


// 解密token
const expressJWT = require('express-jwt')
const config = require('./config')
app.use(expressJWT({ secret: config.jwtSecretkey }).unless({ path: [/^\/api/] }))



app.use((req, res, next) => {
    res.cc = function (err, status = 1) {
        res.send({
            status,
            msg: err instanceof Error ? err.msg : err
        })
    }
    next()
})
// 引入router
const router = require('./router/user')
app.use('/api', router)


app.use((err, req, res, next) => {
    if (err.name == 'UnauthorizedError') return res.cc('请登录！身份认证失败')
})


app.listen(80, () => {
    console.log('http://127.0.0.1:80');
})